import * as echarts from '../../ec-canvas/echarts';
const app = getApp()
const utils = require('../../utils/util.js')
//电池阀
function setEleOption(chart, options) {
  const option = {
    title: {
      left: 24,
      text: '电池阀监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      },
      subtext: '次数（次）',
      subtextStyle: {
        color: '#666666',
        fontSize: 11
      }
    },
    legend: {
      right: 24,
      data: options.legend
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        console.log(params);
        return (params[0].data[0] + '\n' +"开启:" +  params[0].data[1] + "次");
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    yAxis: {
      show: false,
      boundaryGap: [0, '100%'],
    },
    series: options.series, 
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 100,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ]
  };
  chart.setOption(option);
}

function setTempOption(chart, options) {
  const option = {
    title: {
      left: 8,
      text: '温度/温度监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      }
    },
    legend: {
      right: 24,
      data: ['温度', '湿度']
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        console.log(params);
        return (params[0].data[0] + '\n' +"湿度:" +  params[0].data[1] + "%")
          + '\n' +"温度:" +  params[1].data[1] + "℃";
      },
      axisPointer: {
        type: 'cross'
      },
      feature: {
        dataView: {show: true, readOnly: false},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    yAxis: [
      {
          type: 'value',
          name: '湿度(%)',
          min: 0,
          max: 100,
          position: 'right',
          axisLine: {
              show: true,
              lineStyle: {
                  color: '#5470C6',
                  fontSize: 12
              }
          },
          axisLabel: {
              formatter: '{value}'
          }
      },
      {
          type: 'value',
          name: '温度(°C)',
          min: 0,
          max: 100,
          position: 'left',
          axisLine: {
              show: true,
              lineStyle: {
                  color: '#91CC75',
                  fontSize : 8
              }
          },
          axisLabel: {
              formatter: '{value}'
          }
      }
    ],
    series: options.series, 
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 100,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ]
  };
  chart.setOption(option);
}

function setQitiOption(chart, options) {
  const option = {
    title: {
      left: 8,
      text: '气体监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      }
    },
    legend: {
      right: 24,
      data: ['O2', 'H2S']
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        console.log(params);
        return (params[0].data[0] + '\n' +"O2:" +  params[0].data[1] + "%VOL")
          + '\n' +"H2S:" +  params[1].data[1] + "ppm";
      },
      axisPointer: {
        type: 'cross'
      },
      feature: {
        dataView: {show: true, readOnly: false},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '气体(ppm)',
      position: 'left',
      axisLine: {
          show: true,
          lineStyle: {
              color: '#5470C6',
              fontSize: 12
          }
      },
      axisLabel: {
          formatter: '{value}'
      }
    },
    series: options.series, 
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 100,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ]
  };
  chart.setOption(option);
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    deviceId : 0,
    winWidth: 0,
    winHeight: 0,
    currentTab: 0,
    headerOxtName : "", //头部的几个文案-牛舍名字
    headerAreaName : "",//头部的几个文案-区域名字
    headerDeviceName : "", //头部的几个文案-设备名称
    headerDeviceNo : "",
    ganyingDataList : [],
    gangyingHasNext : false,
    page: 1,
    eleEc: {
      lazyLoad: true
    },
    tempEc: {
      lazyLoad: true
    },
    qitiEc:{
      lazyLoad : true
    },
    eleBeginTime: '', // 开始日期
    eleEndTime: '', // 结束日期
    eleDetailDataList : [],
    tempBeginTime : '',
    tempEndTime : '',
    tempDetailDataList : [],
    qitiBeginTime : '',
    qitiEndTime : '',
    qitiDetailDataList : []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      deviceId: options.deviceId || 0
    });
    that.initDetailData();
    /**
     * 获取当前设备的宽高
     */
    wx.getSystemInfo( {
        success: function( res ) {
            that.setData( {
                winWidth: res.windowWidth,
                winHeight: res.windowHeight
            });
        }
    });
    that.eleEcComponent = this.selectComponent('#ele-mychart-dom-line');
    that.tempEcComponent = this.selectComponent('#temp-mychart-dom-line');
    that.qitiEcComponent = this.selectComponent('#qiti-mychart-dom-line');

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.gangyingHasNext && this.data.currentTab == 0) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadGanyingList(this.data.page);
    }
  },
  swichNav: function( e ) {
    console.log(e);
    var that = this;
    if( this.data.currentTab === e.target.dataset.current ) {
        return false;
    } else {
      if (e.target.dataset.current == 1) { //进行加载开启次数
        that.loadEleChart();
        that.loadEleDetailList();
      } else if (e.target.dataset.current == 2) {
        that.loadTempChart();
        that.loadTemplateList();
      } else if (e.target.dataset.current == 3) {
        that.loadQitiChart();
        that.loadQitiList();
      }
      that.setData( {
          currentTab: e.target.dataset.current
      })
    }
  },
  bindChange: function( e ) {
      var that = this;
      that.setData( { currentTab: e.detail.current });
      if (e.detail.current == 1) { //进行加载开启次数
        that.loadEleChart();
        that.loadEleDetailList();
      } else if (e.detail.current == 2) {
        that.loadTempChart();
        that.loadTemplateList();
      } else if (e.detail.current == 3) {
        that.loadQitiChart();
        that.loadQitiList();
      }
  },
  initDetailData : function() {
    let that = this;
    let p1 = utils.promiseGet('/wx/property/getDeviceInfoById', {"deviceId" : this.data.deviceId}),
      p2 = utils.promisePost('/wx/device/spray/getWorkList', {"deviceId" : this.data.deviceId, "page" : 1, "pageSize" : 10});
    Promise.all([p1, p2]).then((result) => {
      //p1
      if (result && result[0] && result[0].code == 200) {
        let deviceInfo = result[0].data || {};
        that.setData({
          headerOxtName : deviceInfo.oxtName || '',
          headerAreaName : deviceInfo.oxtAreaName || '',
          headerDeviceNo : deviceInfo.dceNo || '',
          headerDeviceName : deviceInfo.name || ''
        });
      }
      //p2
      if (result && result[1] && result[1].code == 200) {
        let workData = result[1].data;
        let ganyingList = [], gangyingHasNext = false;
        if (workData.rows.length > 0) {
          for (let i = 0; i < workData.rows.length; i++) {
            let itemRow = {
              "time" : workData.rows[i].createTime,
              "content" : that.formatGanyingqiWorkStatus(workData.rows[i].exceptionType)
            };
            ganyingList.push(itemRow);
          }
          gangyingHasNext = true;
        } else {
          gangyingHasNext = false;
          ganyingList = [{
            "time" : "暂无数据",
            "content" : ""
          }];
        }
        that.setData({
          ganyingDataList: ganyingList,
          gangyingHasNext: gangyingHasNext
        });
      }

    }).catch(function(e){
        console.log(e);
    });
  },
  loadGanyingList: function (page) {
    let that = this;
    let getSprayWorkListParams = {
      "deviceId": that.data.deviceId,
      "page": page,
      "pageSize": 10,
    };
    utils.promisePost('/wx/device/spray/getWorkList', getSprayWorkListParams).then(res => {
      console.log(res);
      let ganyingList = that.data.ganyingDataList;
      let gangyingHasNext = that.data.gangyingHasNext;
      if (page == 1) {
        ganyingList = [];
      }
      if (res.code == 200) {
        let result = res.data;
        if (result.rows.length > 0) {
          for (let i = 0; i < result.rows.length; i++) {
            let itemRow = {
              "time" : result.rows[i].createTime,
              "content" : that.formatGanyingqiWorkStatus(result.rows[i].exceptionType)
            };
            ganyingList.push(itemRow);
          }
          gangyingHasNext = true;
        } else {
          gangyingHasNext = false;
        }
      } else {
      }
      this.setData({
        ganyingDataList: ganyingList,
        gangyingHasNext: gangyingHasNext
      });
    }).catch(e => {
      console.log(e);
    });
  },
  formatGanyingqiWorkStatus(exceptionType) {
    if (exceptionType == 0) {
        return '感应器正常';
    }
    let strArr = [];
    if (exceptionType & 1 == 1) {
      strArr.push('传感器');
    }
    if ((exceptionType >> 1) & 1 == 1) {
      strArr.push('电磁阀');
    }
    if ((exceptionType >> 2) & 1 == 1) {
      strArr.push('气体传感器');
    }
    return strArr.toString() + "异常";
  },
  initEleChart: function (series) {
    this.eleEcComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setEleOption(chart, {
        series
      });
      // // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      // this.chart = chart;
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  loadEleChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "deviceId" : that.data.deviceId,
          "beginTime" : that.data.eleBeginTime ? (that.data.eleBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.eleEndTime ? (that.data.eleEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    utils.promiseGet('/wx/device/spray/getEleOpenTimesByDay', params).then(function(res){
      let todayData = {
        name : "次数",
        data: [],
        //smooth: true,
        type: 'line',
        areaStyle: {}
      };
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var todayArr = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var item = new Array(res.data.list[i].uploadDate, res.data.list[i].eleOpenNum);
            todayArr.push(item);
          }
          todayData.data = todayArr;
        }
      }
      if (todayData.data.length == 0) {
        todayData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      var series = new Array(todayData);
      console.log(series);
      that.initEleChart(series);
    }).catch(function(e){
      console.log(e);
    });
  },
  handleEleBeginTimeChange(e) {
    this.setData({
      eleBeginTime: e.detail
    })
    this.handleEleTimeChange()
  },

  handleEleEndTimeChange(e) {
    this.setData({
      eleEndTime: e.detail
    })
    this.handleEleTimeChange()
  },

  handleEleTimeChange() {
    let that = this;
    const { eleBeginTime, eleEndTime } = this.data
    if (eleBeginTime && eleEndTime) {
      that.loadEleChart();
    }
  },
  loadEleDetailList : function() {
    let that = this;
    let params = {
      "deviceId" : that.data.deviceId,
      "page" : 1,
      "pageSize" : 5
    };
    utils.promiseGet('/wx/device/spray/getList', params).then(function(res){
      console.log(res);
      if (res.code == 200 && res.data) {
        if (res.data.rows.length > 0) {
          var arr = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            var item = {
              "time" : res.data.rows[i].createTime,
              "num" : res.data.rows[i].eleOpenNum
            };
            arr.push(item);
          }
          that.setData({
            "eleDetailDataList" : arr
          });
        }
      }
    }).catch(function(e){
      console.log(e);
    });
  },
  toEleDetailListPageLog(event) {
    let jumpUrl = '/pages/spray/eleDetaillist?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.headerDeviceNo + 
      "&barnName=" + this.data.headerOxtName +
      "&zoneName=" + this.data.headerAreaName + 
      "&devName=" + this.data.headerDeviceName;
    wx.navigateTo({
      url: jumpUrl
    });
  },
  refreshEleDetailListData(event){
    this.loadEleChart();
    this.loadEleDetailList();
  },
  //温度湿度部分------------
  initTempChart: function (series) {
    this.tempEcComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setTempOption(chart, {
        "series" : series
      });
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  handleTempBeginTimeChange(e) {
    this.setData({
      tempBeginTime: e.detail
    })
    this.handleTempTimeChange()
  },
  handleTempEndTimeChange(e) {
    this.setData({
      tempEndTime: e.detail
    })
    this.handleTempTimeChange()
  },

  handleTempTimeChange() {
    let that = this;
    const { tempBeginTime, tempEndTime } = this.data
    if (tempBeginTime && tempEndTime) {
      that.loadTempChart();
    }
  },
  loadTempChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "deviceId" : that.data.deviceId,
          "beginTime" : that.data.tempBeginTime ? (that.data.tempBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.tempEndTime ? (that.data.tempEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    utils.promiseGet('/wx/device/spray/getTempData', params).then(function(res){
      let shiduSerialData = {
        name: '湿度',
        type: 'line',
        data: []
      }, wenduSerialData = {
        name : "温度",
        data: [],
        type: 'line',
        areaStyle: {}
      }
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var wenduArr = [],shiduArry = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var temp = new  Array(res.data.list[i].updateTime, res.data.list[i].temperature);
            wenduArr.push(temp);
            var wenduitem = new Array(res.data.list[i].updateTime, res.data.list[i].humidity);
            shiduArry.push(wenduitem);
          }
          shiduSerialData.data = shiduArry;
          wenduSerialData.data = wenduArr;
        }
      }
      if (shiduSerialData.data.length == 0) {
        shiduSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (wenduSerialData.data.length == 0) {
        wenduSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }

      var series = new Array(shiduSerialData, wenduSerialData);
      console.log(series);
      that.initTempChart(series);
    }).catch(function(e){
      console.log(e);
    });
  },
  loadTemplateList : function() {
    let that = this;
    let params = {
      "deviceId" : that.data.deviceId,
      "page" : 1,
      "pageSize" : 5
    };
    utils.promiseGet('/wx/device/spray/getList', params).then(function(res){
      console.log(res);
      if (res.code == 200 && res.data) {
        if (res.data.rows.length > 0) {
          var arr = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            var item = {
              "time" : res.data.rows[i].createTime,
              "shidu" : res.data.rows[i].humidity,
              "wendu" : res.data.rows[i].temperature
            };
            arr.push(item);
          }
          that.setData({
            "tempDetailDataList" : arr
          });
        }
      }
    }).catch(function(e){
      console.log(e);
    });
  },
  toTempDetailListPageLog(event) {
    let jumpUrl = '/pages/spray/tempDetaillist?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.headerDeviceNo + 
      "&barnName=" + this.data.headerOxtName +
      "&zoneName=" + this.data.headerAreaName + 
      "&devName=" + this.data.headerDeviceName;
    wx.navigateTo({
      url: jumpUrl
    });
  },
  refreshTempDetailListData(event){
    this.loadEleChart();
    this.loadEleDetailList();
  },
  ///气体----------
  initQitiChart: function (series) {
    this.qitiEcComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setQitiOption(chart, {
        "series" : series
      });
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  handleQitiBeginTimeChange(e) {
    this.setData({
      qitiBeginTime: e.detail
    })
    this.handleQitiTimeChange()
  },
  handleQitiEndTimeChange(e) {
    this.setData({
      qitiEndTime: e.detail
    })
    this.handleQitiTimeChange()
  },

  handleQitiTimeChange() {
    let that = this;
    const { qitiBeginTime, qitiEndTime } = this.data
    if (qitiBeginTime && qitiEndTime) {
      that.loadQitiChart();
    }
  },
  loadQitiChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "deviceId" : that.data.deviceId,
          "beginTime" : that.data.qitiBeginTime ? (that.data.qitiBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.qitiEndTime ? (that.data.qitiEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    utils.promiseGet('/wx/device/spray/getTempData', params).then(function(res){
      let o2SerialData = {
        name: 'O2',
        type: 'line',
        data: []
      }, h2sSerialData = {
        name : "H2S",
        data: [],
        type: 'line',
        areaStyle: {}
      }
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var o2Arr = [],h2sArry = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var temp = new  Array(res.data.list[i].updateTime, res.data.list[i].otwo);
            o2Arr.push(temp);
            var h2sitem = new Array(res.data.list[i].updateTime, res.data.list[i].htwos);
            h2sArry.push(h2sitem);
          }
          o2SerialData.data = o2Arr;
          h2sSerialData.data = h2sArry;
        }
      }
      if (o2SerialData.data.length == 0) {
        o2SerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (h2sSerialData.data.length == 0) {
        h2sSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }

      var series = new Array(o2SerialData, h2sSerialData);
      console.log(series);
      that.initQitiChart(series);
    }).catch(function(e){
      console.log(e);
    });
  },
  loadQitiList : function() {
    let that = this;
    let params = {
      "deviceId" : that.data.deviceId,
      "page" : 1,
      "pageSize" : 5
    };
    utils.promiseGet('/wx/device/spray/getList', params).then(function(res){
      console.log(res);
      if (res.code == 200 && res.data) {
        if (res.data.rows.length > 0) {
          var arr = [];
          for (var i = 0; i < res.data.rows.length; i++) {
            var item = {
              "time" : res.data.rows[i].createTime,
              "o2" : res.data.rows[i].otwo,
              "h2s" : res.data.rows[i].htwos
            };
            arr.push(item);
          }
          that.setData({
            "qitiDetailDataList" : arr
          });
        }
      }
    }).catch(function(e){
      console.log(e);
    });
  },
  toQitiDetailListPageLog(event) {
    let jumpUrl = '/pages/spray/qitiDetaillist?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.headerDeviceNo + 
      "&barnName=" + this.data.headerOxtName +
      "&zoneName=" + this.data.headerAreaName + 
      "&devName=" + this.data.headerDeviceName;
    wx.navigateTo({
      url: jumpUrl
    });
  },
  refreshQitiDetailListData(event){
    this.loadEleChart();
    this.loadEleDetailList();
  },
})